import Vue from 'vue'
import axios from 'axios'
import qs from "qs"
import router from '../../router'
import { MessageBox,Toast,Indicator } from 'mint-ui';
//http request 请求拦截器，有token值则配置上token值
axios.interceptors.request.use(
	config => {
    var isPro = process.env.NODE_ENV === 'production'//production == 生产，development ==开发
    if(isPro){
      config.url = preUrl+config.url
    }
		if (localStorage.getItem('authorization')&&config.url.indexOf('/bmbs-user/login')==-1) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
        config.headers.Authorization = localStorage.getItem('authorization');
    }
    config.headers.serviceType = '2'
		return config;
	},
	err => {
		return Promise.reject(err);
	}
);

//响应拦截器
axios.interceptors.response.use(function (response) {
    // 在接收响应做些什么，例如跳转到登录页
    if(response){
		let authorization = response.headers.authorization;

		if(authorization != '' && authorization != undefined){
			localStorage.setItem('authorization',authorization);
		}
	}
    return response;
  }, function (error) {
    // 对响应错误做点什么
	if (error.response.statusCode === 401) {
		MessageBox.confirm('登录过期，跳转到登录页?').then(action => {
			localStorage.removeItem('authorization');
			router.push('/login');
		});
	} else if (error.response.statusCode) {
		Toast('服务器错误！')
	}
    return Promise.reject(error);
  }
);

export function get(url, params = {}) {
	return new Promise((resolve /*,reject*/ ) => {
		axios.get(url, {
				params: params
			})
			.then(response => {
				if(response.data.statusCode == 200){
					resolve(response);
				}else{
           Indicator.close();
					Toast(response.data.msg)
				}
			})
			.catch(err => {
         Indicator.close();
				resolve(err)
				//resolve(err);
				//Toast('请求超时')
			})
	})
}
export function post(url, data = {}) {
	return new Promise((resolve ,reject ) => {
		axios.post(url, data)
			.then(response => {
				if(response.data.statusCode == 200){
					resolve(response);
				}else{
           Indicator.close();
					Toast(response.data.msg)
				}
			}, err => {
         Indicator.close();
					resolve(err)
					//Toast(err.response.data.msg)

			})
	})
}
export function delet(url, data = {}) {
	return new Promise((resolve ,reject ) => {
		axios.delete(url,data)
			.then(response => {
				if(response.data.statusCode == 200){
					resolve(response);
				}else{
					Toast(response.data.msg)
				}
			}, err => {
				Toast('请求超时')
			})
	})
}
export function put(url, data = {}) {
	return new Promise((resolve ,reject ) => {
		axios.put(url, data)
			.then(response => {
				if(response.data.statusCode == 200){
					resolve(response);
				}else{
					Toast(response.data.msg)
				}
			}, err => {
				Toast('请求超时')
			})
	})
}
